package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties minioProperties;

    @Override
    public String fileUpload(MultipartFile file) {
        String f1 = null;
        try {
            long size = file.getSize();
            //从输入流中读取图像数据
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null){
                throw new GuiguException(400,"图片非法，FBI Warning！");
            }
            //创建bucket
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                //进入这里说明没有创建好桶，这里要创建一个桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket '" + minioProperties.getBucketName() + "' already exists.");
            }
            // 创建文件夹名称
            String name = "/" + DateUtil.today() + "/";
            // 获取文件后缀
            String extName = FileUtil.extName(file.getOriginalFilename());
            // 更改文件名称为随机数
            String uuid = IdUtil.randomUUID();
            //拼接
            String f = name + uuid + "." + extName;

            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioProperties.getBucketName()).object(f)
                            .stream(file.getInputStream(), size, -1)
                            .contentType(file.getContentType())
                            .build());
            f1 = minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + f;


        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return f1;
    }

}
